package com.base.thread.demo_31;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition 的简单使用
 * A B C 3个线程任务顺序执行
 * @ClassName: Demo
 * @Description: 
 * @Author xuyou
 * @DateTime 2020年12月17日 下午5:37:37
 */
public class Demo {

	
	private int signal;
	
	Lock lock = new ReentrantLock();
	Condition a = lock.newCondition();
	Condition b = lock.newCondition();
	Condition c = lock.newCondition();
	
	
	public void a() {
		lock.lock();
		while(signal != 0) {
			try {
				a.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("a线程任务执行了");
		signal ++ ;
		//唤醒b线程
		b.signal();
		lock.unlock();
	}
	
	public void b() {
		lock.lock();
		while(signal != 1) {
			try {
				b.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("b线程任务执行了");
		signal ++ ;
		//唤醒c线程
		c.signal();
		lock.unlock();
	}
	
	public void c() {
		lock.lock();
		while(signal != 2) {
			try {
				c.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("c线程任务执行了");
		signal = 0 ;
		//唤醒a线程
		a.signal();
		lock.unlock();
	}
	
	public static void main(String[] args) {
		Demo demo = new Demo();
		A a = new A(demo);
		B b = new B(demo);
		C c = new C(demo);
		
		new Thread(a).start();
		new Thread(b).start();
		new Thread(c).start();
		
	}
	
}

class A implements Runnable {

	private Demo demo;
	
	public A(Demo demo) {
		this.demo = demo;
	}
	@Override
	public void run() {
		while(true) {
			demo.a();
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
			}
		}
	}
}

class B implements Runnable {

	private Demo demo;
	
	public B(Demo demo) {
		this.demo = demo;
	}
	@Override
	public void run() {
		while(true) {
			demo.b();
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
			}
		}
	}
}

class C implements Runnable {

	private Demo demo;
	
	public C(Demo demo) {
		this.demo = demo;
	}
	@Override
	public void run() {
		while(true) {
			demo.c();
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
			}
		}
	}
}